import { login, getUserInfoAccount } from '@/api/user';
import { setToken, getToken } from '@/util';

export default {
  state: {
    factories: [],
    id_token: '',
    roles: '',
    token: getToken(),
    userName: '',
    account: [], // 个人信息
    access: [], // 权限组
  },
  mutations: {
    setAvator(state, avatorPath) {
      state.avatorImgPath = avatorPath;
    },
    setUserId(state, id) {
      state.userId = id;
    },
    setUserName(state, name) {
      state.userName = name;
    },
    setAccess(state, access) {
      state.access = access;
    },
    setToken(state, token) {
      state.id_token = token;
      state.token = token;
      setToken(token);
    },
    setFactories(state, value) {
      state.factories = value;
    },
    setRoles(state, value) {
      state.roles = value;
    },
    setAccount(state, value) {
      state.account = value;
    },
  },
  actions: {
    // 登录`
    handleLogin({ commit }, { userName, password }) {
      return new Promise((resolve, reject) => {
        login({ userName, password })
          .then(res => {
            const { data } = res;
            commit('setToken', data.id_token);
            commit('setFactories', data.factories);
            commit('setRoles', data.roles);
            resolve();
          })
          .catch(err => {
            reject(err);
          });
      });
    },

    // 获取用户相关信息
    getUserInfo({ commit, state }) {
      console.log('getUserInfo--获取用户相关信息');
      return new Promise((resolve, reject) => {
        getUserInfoAccount(state.token || state.id_token)
          .then(res => {
            const { data } = res;
            commit('setAccount', data);
            commit('setUserName', data.login);
            commit('setAccess', data.authorities);
            resolve(data);
          })
          .catch(err => {
            commit('setToken', '');
            window.location.reload();
            reject(err);
          });
      });
    },

    // // 退出登录
    // handleLogOut({ state }) {
    //   return new Promise((resolve, reject) => {
    //     logout(state.token)
    //       .then(() => {
    //         resolve();
    //       })
    //       .catch(err => {
    //         reject(err);
    //       });
    //     // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
    //     // commit('setToken', '')
    //     // commit('setAccess', [])
    //     // resolve()
    //   });
    // },
  },
};
